package com.tiaoshi.thenwhat.common.dao;

import java.util.List;
import java.util.regex.Pattern;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Component;

import com.tiaoshi.thenwhat.common.entity.common.Person;

@Component("personRepository")
public class PersonRepository implements AbstractRepository {
	@Autowired
	private MongoTemplate template;

	public List<Person> findAll() {
		return template.find(new Query(), Person.class);
	}

	public void findAndModify(String id) {
		template.updateFirst(new Query(Criteria.where("id").is(id)),
				new Update().inc("age", 3), Person.class);
	}

	public List<Person> findByRegex(String regex) {
		Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
		Criteria criteria = new Criteria("name").regex(pattern.toString());
		return template.find(new Query(criteria), Person.class);
	}

	public Person findOne(String id) {
		return template.findOne(
				new Query(Criteria.where("id").is(id)), Person.class);
	}
	
	public Object findById(String id,Class entityClass){
		return template.findById(id, entityClass);
	}

	public void insert(Person person) {
		template.insert(person);
	}

	public void removeAll() {
		List<Person> list = this.findAll();
		if (list != null) {
			for (Person person : list) {
				template.remove(person);
			}
		}
	}

	public void removeOne(String id) {
		Criteria criteria = Criteria.where("id").in(id);
		if (criteria == null) {
			Query query = new Query(criteria);
			if (query != null
					&& template.findOne(query, Person.class) != null)
				template.remove(
						template.findOne(query, Person.class));
		}
	}

}
